<template>
  <view class="star-rating">
    <view 
      v-for="(star, index) in stars" 
      :key="index" 
      class="star-item"
      @click="handleClick(index)"
    >
      <text 
        class="star-icon"
        :style="{ 
          fontSize: size + 'rpx',
          color: star.filled ? color : '#E5E5E5'
        }"
      >
        {{ star.filled ? '★' : '☆' }}
      </text>
    </view>
  </view>
</template>

<script>
export default {
  name: 'StarRating',
  props: {
    // 当前评分（0-5）
    value: {
      type: Number,
      default: 0
    },
    // 是否只读
    readonly: {
      type: Boolean,
      default: false
    },
    // 是否支持半星
    allowHalf: {
      type: Boolean,
      default: false
    },
    // 星星大小（rpx）
    size: {
      type: Number,
      default: 40
    },
    // 星星颜色
    color: {
      type: String,
      default: '#FFB400'
    }
  },
  data() {
    return {
      currentValue: this.value
    };
  },
  computed: {
    stars() {
      const stars = [];
      for (let i = 0; i < 5; i++) {
        stars.push({
          filled: i < Math.floor(this.currentValue),
          half: this.allowHalf && (i === Math.floor(this.currentValue)) && (this.currentValue % 1 !== 0)
        });
      }
      return stars;
    }
  },
  watch: {
    value(newVal) {
      this.currentValue = newVal;
    }
  },
  methods: {
    handleClick(index) {
      if (this.readonly) {
        return;
      }
      
      const newValue = index + 1;
      this.currentValue = newValue;
      this.$emit('change', newValue);
    }
  }
};
</script>

<style scoped>
.star-rating {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.star-item {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.star-icon {
  line-height: 1;
  font-style: normal;
  transition: color 0.2s ease;
}
</style>

